﻿using Microsoft.Practices.Unity;
using Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WebIOCService.Interface;

namespace MyWebTest.Controllers
{
    public abstract class DDDDD
    {
        public abstract string GetString();

        public static string Dget { get; set; }
        public static void Add()
        {

        }
    }

    public class EEE : DDDDD
    {
        public override string GetString()
        {
            return "";
        }
    }

    public class DataList
    {
        public string Name { get; set; }
    }

    public class DataItem
    {

    }

    public class HomeController : Controller
    {

        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <returns></returns>
        private string GetMacAddress()
        {
            try
            {
                string userip = System.Web.HttpContext.Current.Request.UserHostAddress;
                string strClientIP = System.Web.HttpContext.Current.Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP); //目的地的ip
                Int32 lhost = inet_addr("");   //本地服务器的ip
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                if (mac_src == "0")
                {
                    return userip;
                }
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }
                string mac_dest = "";
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }

                return mac_dest;
            }
            catch
            {

            }
            return "无法识别";
        }

        ///<summary>
        /// 获取客户端计算机名称
        ///</summary>
        ///<returns></returns>
        public string GetClientComputerName()
        {
            string clientIP = System.Web.HttpContext.Current.Request.UserHostAddress;//获取客户端的IP主机地址
            IPHostEntry hostEntry = Dns.GetHostEntry(clientIP);//获取IPHostEntry实体
            return hostEntry.HostName;//返回客户端计算机名称
        }

        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <returns></returns>
        public string GetClientIP()
        {
            string result = String.Empty;
            result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (null == result || result == String.Empty)
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            if (null == result || result == String.Empty)
            {
                return "0.0.0.0";
            }
            return result;
        }

        /// <summary>
        /// 获取操作系统版本号
        /// </summary>
        /// <returns></returns>
        public string SystemCheck()
        {
            string Agent = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
            if (Agent.IndexOf("NT 4.0") > 0)
                return "Windows NT ";
            else if (Agent.IndexOf("NT 5.0") > 0)
                return "Windows 2000";
            else if (Agent.IndexOf("NT 5.1") > 0)
                return "Windows XP";
            else if (Agent.IndexOf("NT 5.2") > 0)
                return "Windows 2003";
            else if (Agent.IndexOf("NT 6.0") > 0)
                return "Windows Vista";
            else if (Agent.IndexOf("NT 7.0") > 0)
                return "Windows 7";
            else if (Agent.IndexOf("NT 8.0") > 0)
                return "Windows 8";
            else if (Agent.IndexOf("WindowsCE") > 0)
                return "Windows CE";
            else if (Agent.IndexOf("NT") > 0)
                return "Windows NT ";
            else if (Agent.IndexOf("9x") > 0)
                return "Windows ME";
            else if (Agent.IndexOf("98") > 0)
                return "Windows 98";
            else if (Agent.IndexOf("95") > 0)
                return "Windows 95";
            else if (Agent.IndexOf("Win32") > 0)
                return "Win32";
            else if (Agent.IndexOf("Linux") > 0)
                return "Linux";
            else if (Agent.IndexOf("SunOS") > 0)
                return "SunOS";
            else if (Agent.IndexOf("Mac") > 0)
                return "Mac";
            else if (Agent.IndexOf("Windows") > 0)
                return "Windows";
            return "未知类型";
        }

        public ActionResult Index()
        {
            var request = System.Web.HttpContext.Current.Request;
            if (request != null)
            {
                string str = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    浏览器ID = request.Browser.Id,
                    浏览器名 = request.Browser.Browser,
                    浏览器运行平台 = request.Browser.Platform,
                    浏览器版本 = request.Browser.Version,

                    客户端上次请求的URL路径 = request.UrlReferrer + "",
                    客户端当前请求的URl = request.Url + "",
                    客户端浏览器的原始用户代理信息 = request.UserAgent,
                    客户端的ip主机地址 = request.UserHostAddress,
                    客户端的DNS名称 = request.UserHostName,
                    客户端计算机名称 = GetClientComputerName(),
                    客户端操作系统版本号 = SystemCheck(),
                    客户端IP = GetClientIP(),
                    客户端MAC = GetMacAddress()
                });
                WritOperateLog(str);
            }
            return View();
        }


        //
        // GET: /Home/

        [Dependency]
        public ICouponService CouponService { get; set; }

        [HttpGet]
        public JsonResult GetCouponName(string code)
        {
            EEE.Add();
            EEE.Dget = "";
            couponservice.couponserviceService service = new couponservice.couponserviceService();
            var obj = service.getCouponList();
            return new JsonResult()
            {
                Data = obj,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        public ActionResult Default()
        {
            Queue q = new Queue();

            byte s = 0;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            SysOperateLog3 obj1 = new SysOperateLog3();
            SysOperateLog o1 = new SysOperateLog();
            o1.Msg = "o1";
            obj1.obj = o1;
            obj1.id = 1;
            obj1.Msg3 = "1";
            Newtonsoft.Json.JsonConvert.SerializeObject(obj1);
            sw.Stop();
            WritOperateLog("1序列化耗时：" + sw.ElapsedMilliseconds);

            sw.Start();
            SysOperateLog3 obj2 = new SysOperateLog3();
            SysOperateLog1 o2 = new SysOperateLog1();
            o2.Msg1 = "o2";
            obj2.obj = o2;
            obj2.id = 2;
            obj2.Msg3 = "2";
            Newtonsoft.Json.JsonConvert.SerializeObject(obj2);
            sw.Stop();
            WritOperateLog("2序列化耗时：" + sw.ElapsedMilliseconds);

            sw.Start();
            SysOperateLog3 obj3 = new SysOperateLog3();
            SysOperateLog2 o3 = new SysOperateLog2();
            o3.Msg2 = "o3";
            obj3.obj = o3;
            obj3.id = 3;
            obj3.Msg3 = "3";
            Newtonsoft.Json.JsonConvert.SerializeObject(obj3);
            sw.Stop();
            WritOperateLog("3序列化耗时：" + sw.ElapsedMilliseconds);


            //WritOperateLog("异步写入文件开始");

            //System.Threading.Thread task = new System.Threading.Thread(DelegateSynUpdateStockTime);
            //task.Start(100);

            ////new System.Threading.Tasks.Task(() =>
            ////{
            ////    DelegateSynUpdateStockTime(100);
            ////}).Start();

            //WritOperateLog("异步写入文件结束");

            return View();
        }

        /// <summary>
        /// 异步更新活动时间
        /// </summary>
        /// <param name="data"></param>
        void DelegateSynUpdateStockTime(object data)
        {
            if (data != null)
            {
                int obj = Convert.ToInt32(data);
                for (int i = 0; i < obj; i++)
                {
                    WritOperateLog("异步写入文件" + i);
                    System.Threading.Thread.Sleep(6 * 1000);
                }
            }
        }

        [HttpPost]
        public FileResult DownLoadFile(HttpPostedFileBase fileData)
        {
            string name = fileData.FileName;
            int l = fileData.ContentLength;
            byte[] bytes = new byte[l];
            fileData.InputStream.Read(bytes, 0, l);
            //return Json(bytes);
            return File(bytes, "application/ms-excel", name);
        }

        public ActionResult Index1(int batchId = 0)
        {
            WritOperateLog("调用开始");
            string jsdata = "";
            if (batchId == 0)
            {
                List<int> ids = new List<int>();
                ids.Add(1);
                ids.Add(2);
                ids.Add(3);
                ids.Add(1374528);
                ids.Add(1374517);
                var list = CouponService.GetCouponBatchs(ids, out jsdata);
                if (list != null && list.Count > 0)
                {
                    jsdata = Newtonsoft.Json.JsonConvert.SerializeObject(list);
                }
            }
            else
            {
                CouponBatch coupon = CouponService.GetCouponBatch(batchId, out jsdata);
                if (coupon != null && jsdata == "")
                {
                    jsdata = Newtonsoft.Json.JsonConvert.SerializeObject(coupon);
                }
            }

            WritOperateLog("调用结束");

            return Content(jsdata);
        }

        object locker = new object();
        Queue _que = new Queue();
        void EnqueueMessage(SysOperateLog data)
        {
            _que.Enqueue(data);
        }

        void SysAddOperateLog(object data)
        {
            var obj = (SysOperateLog)data;
            if (obj != null)
            {
                lock (locker)
                {
                    System.IO.File.AppendAllText(@"D:\logs\log.txt", DateTime.Now.ToString() + "\t" + obj.Msg + "\r\n");
                }
            }
        }

        /// <summary>
        /// 添加操作日志
        /// </summary>
        /// <param name="paids"></param>
        /// <param name="opUser"></param>
        /// <param name="logtxt"></param>
        /// <returns></returns>
        public void WritOperateLog(string logtxt)
        {
            if (string.IsNullOrEmpty(logtxt)) return;
            var obj = new SysOperateLog
            {
                Msg = logtxt
            };
            System.Threading.Thread task = new System.Threading.Thread(SysAddOperateLog);
            task.Start(obj);
        }
    }
}
